package kr.hyosang.dkbs.kiosk.server.data;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import kr.hyosang.dkbs.kiosk.server.data.entity.NewsEntity;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

public class News {
	public static final String KIND_NAME = "News";
	
	public static final String PROP_TITLE = "title";
	public static final String PROP_CONTENT = "content";
	public static final String PROP_START_DATE = "start_date";
	public static final String PROP_END_DATE = "end_date";
	
	private DatastoreService mDatastore = null;
	
	public News() {
		mDatastore = DatastoreServiceFactory.getDatastoreService();
		
	}
	
	public void addEntity(NewsEntity item) {
		Entity entity = new Entity(KIND_NAME);
		entity.setProperty(PROP_TITLE, item.title);
		entity.setProperty(PROP_CONTENT, item.content);
		entity.setProperty(PROP_START_DATE, item.startDate);
		entity.setProperty(PROP_END_DATE, item.endDate);
		
		mDatastore.put(entity);
	}
	
	public List<NewsEntity> getList(boolean bNow) {
		Query q = new Query(KIND_NAME);
		
		if(bNow) {
			//현재 게시중인 목록만 반환
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String nowDate = sdf.format(Calendar.getInstance().getTime());
			
			Filter edFilter = new FilterPredicate(PROP_END_DATE,
					FilterOperator.GREATER_THAN_OR_EQUAL,
					nowDate);
			
			q = q.setFilter(edFilter);
		}
		
		q = q.addSort(PROP_END_DATE, SortDirection.DESCENDING)
				.addSort(PROP_START_DATE, SortDirection.ASCENDING)
				.addSort(PROP_TITLE);
		
		PreparedQuery pq = mDatastore.prepare(q);
		
		ArrayList<NewsEntity> list = new ArrayList<>();
		
		for(Entity entity : pq.asIterable()) {
			NewsEntity item = new NewsEntity();
			item.idName = String.valueOf(entity.getKey().getId());
			item.title = (String)entity.getProperty(PROP_TITLE);
			item.content = (String)entity.getProperty(PROP_CONTENT);
			item.startDate = (String)entity.getProperty(PROP_START_DATE);
			item.endDate = (String)entity.getProperty(PROP_END_DATE);
			
			list.add(item);
		}
		
		return list;
	}
	
	public List<NewsEntity> getCurrentList() {
		return getList(true);
	}
	
	public List<NewsEntity> getList() {
		return getList(false);
	}
	

}
